#!/usr/bin/env python

# Search for person in phonebook
# Author: Miki Tebeka <miki.tebeka@gmail.com>
# License: BSD (see LICENSE)

# Phonebook is just a simple text file with one name + phone per line
# AA               323-525-0018    [Car insurance]
# CheeseCake       310-278-7279    [In Beverly]       
# ...

import re
from os.path import join, isfile
from user import home

def main(argv=None):
    if argv is None:
        import sys
        argv = sys.argv

    from optparse import OptionParser

    parser = OptionParser("usage: %prog QUERY")
    parser.add_option("-p", help="name of phonebook", default="",
                      dest="phonebook")

    opts, args = parser.parse_args(argv[1:])
    if len(args) != 1:
        parser.error("wrong number of arguments") # Will exit

    try:
        find = re.compile(args[0], re.I).search
    except re.error:
        raise SystemExit("error: bad search expression - %s" % args[0])

    if not opts.phonebook:
        opts.phonebook = join(home, ".phonebook")

    if not isfile(opts.phonebook):
        raise SystemExit("error: can't find phonebook %s" % opts.phonebook)

    found = 0
    for line in open(opts.phonebook):
        if find(line):
            found = 1
            print line.rstrip()

    if not found:
        raise SystemExit("error: %s not found" % args[0])

if __name__ == "__main__":
    main()
